package org.kingtop.action.bind;

import org.apache.shiro.SecurityUtils;
import org.kingtop.action.annotation.CurrentUser;
import org.kingtop.cache.app.UserCacheUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * <p>
 * 用于绑定@CurrentUser的方法参数解析器
 * <p>
 * User: cjb
 * <p>
 * Date: 17-12-9 20:40
 * <p>
 * Version: 1.1
 */
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

	public CurrentUserMethodArgumentResolver() {
	}

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		if (parameter.hasParameterAnnotation(CurrentUser.class)) {
			return true;
		}
		return false;
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		String username = (String) SecurityUtils.getSubject().getPrincipal();
		Object user = UserCacheUtil.get(username);
		if (user != null) {
			return user;
		}
		CurrentUser currentUserAnnotation = parameter.getParameterAnnotation(CurrentUser.class);
		if (currentUserAnnotation != null) {
			return webRequest.getAttribute(currentUserAnnotation.value(), NativeWebRequest.SCOPE_SESSION);
		}
		return null;
	}
}
